package com.yanqu.road.server.gameplayer.module.activity.springunionbanquet;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.springunionbanquet.config.SpringUnionBanquetAwardInfo;
import com.yanqu.road.entity.activity.springunionbanquet.config.SpringUnionBanquetConfig;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.pb.activity.SpringUnionBanquetProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.logic.activity.BaseActivityData;
import com.yanqu.road.server.logic.activity.condition.BaseActivityCondition;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.springunionbanquet.SpringUnionBanquetMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.Map;

public class SpringUnionBanquetModule extends GeneralModule {

    public SpringUnionBanquetModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        return true;
    }

    @Override
    public void loginSendMsg() {

    }

    @Override
    public void afterLogin() {

        if(!SystemOpenMgr.systemOpen(player, eSystemId.SpringBanquet.getValue())){
            return;
        }
        SpringUnionBanquetConfig config = SpringUnionBanquetMgr.getConfig();
        if(config == null){
            return;
        }
        syncConfig(config);


        String unionUid = player.getUserInfo().getUnionUid();
        //活动期间
        if(!StringUtils.isNullOrEmpty(unionUid) && ActivityMgr.activityInTime(config.getActivityInfo())) {
            SpringUnionBanquetProto.CrossSpringUnionBanquetLoginListReqMsg.Builder crossReq = SpringUnionBanquetProto.CrossSpringUnionBanquetLoginListReqMsg.newBuilder();
            crossReq.setActivityId(config.getActivityId());
            crossReq.setUnionUid(unionUid);
            for (Map.Entry<Long, CrossUnionMember> entry : CrossUnionMgr.getUnionMemberMap(unionUid).entrySet()) {
                crossReq.addMember(entry.getKey());
            }
            player.sendPacket(Protocol.C_SPRING_UNION_BANQUET_LOGIN_SYNC, crossReq);
        }
    }

    private void syncConfig(SpringUnionBanquetConfig config) {
        SpringUnionBanquetProto.SpringUnionBanquetConfigSyncMsg.Builder builder = SpringUnionBanquetProto.SpringUnionBanquetConfigSyncMsg.newBuilder();
        for (SpringUnionBanquetAwardInfo info : config.getAwardInfoList()) {
            SpringUnionBanquetProto.SpringUnionBanquetAwardConfigTemp.Builder infoBuilder = SpringUnionBanquetProto.SpringUnionBanquetAwardConfigTemp.newBuilder();
            infoBuilder.setResource(info.getResource());
            infoBuilder.setId(info.getDishId());
            infoBuilder.setOrdinaryAverage(info.getOrdinaryAverage());
            infoBuilder.setSpecialAward(info.getSpecialAward());
            infoBuilder.setName(ServerLanguageMgr.getContent(info.getName(), player.getLanguage()));
            builder.addAward(infoBuilder);
        }
        player.sendPacket(Protocol.U_SPRING_UNION_BANQUET_SYNC_CONFIG, builder);
    }


    public synchronized void resetOneDay(){

        try {
            SpringUnionBanquetConfig config = SpringUnionBanquetMgr.getConfig();
            if(config == null){
                return;
            }
            //领奖期，如果补发也会被清空
            ActivityInfo activityInfo = config.getActivityInfo();

            if(!ActivityMgr.activityInTime(activityInfo)){
                return;
            }
            int activityId = config.getActivityId();

            long todayZeroTime = DateHelper.getTodayZeroTimeStamp();
            long zeroTime = DateHelper.getZeroTimeStamp(activityInfo.getBeginTime() * 1000);
            if (todayZeroTime <= zeroTime) {
                return;
            }
            //活动第几天
            int days = (int)((todayZeroTime - zeroTime) / DateHelper.DAY_MILLIONS);

            //算最近需要重置的天数
            long needResetDay = 0;
            for (Integer resetDay : config.getConditionRestDayList()) {
                if(days >= resetDay){
                    needResetDay = resetDay;
                }
            }

            if(Config.isDebug()) {
                SpringUnionBanquetMgr.getLogger().info("屠苏重置玩家：{}， 重置天数 {}", player.getUserId(), needResetDay);
            }

            if(needResetDay == 0){
                //未到首次重置时间
                return;
            }

            //重置的时间点
            long restZeroTime = (zeroTime + needResetDay * DateHelper.DAY_MILLIONS) / 1000;

            //重置时间未到
            if(restZeroTime > todayZeroTime){
                return;
            }

            Property reward = new Property();

            ActivityModule activityModule = player.getModule(ActivityModule.class);
            BaseActivityData baseActivityData = activityModule.getBaseActivityData(activityId);
            int size = 0;
            for (BaseActivityCondition activityCondition : baseActivityData.getBaseActivityConditionList()) {
                if(activityCondition.getConditionType() == eGamePlayerEventType.SpringBanquetVip.getValue()){
                    size++;
                    int conditionId = activityCondition.getConditionId();
                    UserActivityConditionData userActivityConditionData = baseActivityData.getUserActivityConditionData(conditionId);
                    if(userActivityConditionData == null){
                        continue;
                    }
                    if(userActivityConditionData.getModifyTime() >= restZeroTime){
                        //过了重置时间的，不重置
                        continue;
                    }
                    if(userActivityConditionData.getValue().compareTo(BigInteger.ZERO) == 0){
                        userActivityConditionData.setModifyTime(restZeroTime);
                        SpringUnionBanquetMgr.getLogger().info("屠苏重置玩家：{}， conditionId {} only reset time", userActivityConditionData.getUserId(), conditionId);
                        continue;
                    }

                    if(activityCondition.isCompleted(player)){
                        if(!userActivityConditionData.isGetReward()){
                            //补发奖励
                            reward.addProperty(activityCondition.getActivityConditionInfo().getReward());
                        }else {
                            //领过奖励的，重新监听
                            userActivityConditionData.setGetReward(false);
                            activityCondition.addTrigger(player);
                        }
                    }
                    userActivityConditionData.setValue(BigInteger.ZERO);
                    userActivityConditionData.setModifyTime(restZeroTime);
                    if(Config.isDebug()) {
                        SpringUnionBanquetMgr.getLogger().info("屠苏重置玩家：{}， conditionId {}", userActivityConditionData.getUserId(), conditionId);
                    }
                }
            }
            SpringUnionBanquetMgr.getLogger().info("屠苏重置玩家：{}， conditionId size {}", player.getUserId(), size);
            activityModule.onActivityDataChanged(baseActivityData);
            activityModule.syncChangedActivityData();

            if(!reward.isNothing()){
                String activityName = ActivityMgr.getActivityName(activityInfo, player.getLanguage());
                String mailTitle = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.TREASURE_ACTIVITY_PROGRESS_REWORD_TITLE, player.getLanguage()), activityName);
                String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.TREASURE_ACTIVITY_PROGRESS_REWORD_CONTENT, player.getLanguage()),
                        activityName);
                MailManager.sendMail(player.getUserId(), eMailType.SYSTEM.getValue(), PropertyHelper.parsePropertyToString(reward), mailContent, mailTitle);
            }


        }catch (Exception e){
            SpringUnionBanquetMgr.getLogger().error("", e);
        }
    }

}
